﻿using System.Diagnostics;
using System.Reflection;

namespace XTrace.Compatibility
{
	public sealed class BridgeFromTraceToXTrace : TraceListener
	{
		public BridgeFromTraceToXTrace()
			: this(true)
		{

		}

		public BridgeFromTraceToXTrace(bool addToListeners)
		{
			if (addToListeners)
			{
				Trace.Listeners.Add(this);
			}
		}

		#region Overrides of TraceListener

		string _line;

		public override void Write(string message)
		{
			_line += message;
		}

		public override void WriteLine(string message)
		{
			Write(message);
			Handle(_line);
			_line = null;
		}

		#endregion

		static void Handle(string line)
		{
			//lock (BridgeFromXTraceToTrace.WritingToTraceSync)
			{
				if (!BridgeFromXTraceToTrace.WritingToTrace)
				{
					XTrace.Verbose(line);
				}
			}
		}

//		XTraceLevel GetImportance(string line)
//		{
//			return XTraceLevel.Verbose;
//		}
//
//		string GetEventId(string line)
//		{
//			return "";
//		}

		public static readonly XTraceSource XTrace = new XTraceSource("System.Diagnostics.Trace");

		public static implicit operator XTraceSource (BridgeFromTraceToXTrace bridge)
		{
			return XTrace;
		}
	}
}